package com.song.EMS.wx.controller;

import com.song.EMS.bean.Courier;
import com.song.EMS.bean.Express;
import com.song.EMS.bean.Message;
import com.song.EMS.bean.User;
import com.song.EMS.mvc.ResponseBody;
import com.song.EMS.mvc.ResponseView;
import com.song.EMS.service.impl.CourierServiceImpl;
import com.song.EMS.service.impl.ExpressServiceImpl;
import com.song.EMS.service.impl.UserServiceImpl;
import com.song.EMS.utils.DateFormatUtil;
import com.song.EMS.utils.JsonUtil;
import com.song.EMS.utils.RandomUtil;
import com.song.EMS.wx.controller.bean.Role;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

public class UserController {
    /**
     * 微信端登陆，获取手机验证码
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/loginMSN.do")
    public String LoginMSN(HttpServletRequest request, HttpServletResponse response){
        Message data = null;
        String userPhone = request.getParameter("userPhone");
        //给用户发送短信
        String loginCode = RandomUtil.getRandom();
        System.out.println("您的验证码为" + loginCode);
        if (loginCode != null){
            data = new Message(1,"验证码已发送，请注意查收");
            //将手机号与验证码存再session中
            UserUtils.setUserCode(request,loginCode);
            UserUtils.setUserPhone(request,userPhone);
        }else{
            data = new Message(0,"验证码发送失败，请重新获取验证码");
        }
        return JsonUtil.toJSON(data);
    }

    /**
     * 用户输入验证码登录
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/login.do")
    public  String login(HttpServletRequest request, HttpServletResponse response){
        UserServiceImpl userService = new UserServiceImpl();
        Message data = null;
        String userPhone = request.getParameter("userPhone");
        String code = request.getParameter("code");
        //判断前端用户输入的手机号·验证码 与 后端session中存储的用户手机号·验证码是否一致
        if (code == null || UserUtils.getUserCode(request)==null){
            data = new Message(-1,"你还未获取验证码");
        }else if (UserUtils.getUserPhone(request).equals(userPhone)&&UserUtils.getUserCode(request).equals(code)){
            data = new Message(1,"登录成功");
            //登录后，判断该用户的是普通用户,快递员,还是新用户
            UserUtils.setRole(request,userPhone);
            //更新登录时间
            Role role = UserUtils.getRole(request);
            if (role.getRoleId() == 1){
                //跟新快递员登录时间
                CourierServiceImpl courierService = new CourierServiceImpl();
                courierService.updateLoginTime(userPhone);
            }else if (role.getRoleId() == 2){
                //更新用户登陆时间
                userService.updateLoginTime(userPhone);
            }
        }else {
            data = new Message(0,"您输入的验证码有误，请重新输入");
        }
        return JsonUtil.toJSON(data);
    }

    /**
     * 退出微信端登录
     * @param request
     * @param response
     * @return
     */
    @ResponseView("/wx/loginOut.do")
    public String LoginOut(HttpServletRequest request, HttpServletResponse response){
        //清除登录时session中的数据
        request.getSession().invalidate();
        return "/login.jsp";
    }

    /**
     * 登录后,判断用户的身份
     * 1 快递员  2 普通用户  0 新用户
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/loginInfo.do")
    public String UserInfo(HttpServletRequest request, HttpServletResponse response){
        Message data = null;
        //sha
        UserUtils.setRole(request,UserUtils.getUserPhone(request));
        Role role = UserUtils.getRole(request);

        if (role.getRoleId() == 1){
            data = new Message(1,"快递员",role.getObject());
        }else if (role.getRoleId() == 2){
            data = new Message(2,"普通用户",role.getObject());
        }else{
            data = new Message(0,"新用户",role.getObject());
        }
        return JsonUtil.toJSON(data);
    }

    /**
     * 用户快递的展示（未取  已取）
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/expressList.do")
    public String expressList(HttpServletRequest request, HttpServletResponse response){
        Map map = null;
        Message data = null;
        //该用户的手机号
        String userPhone = UserUtils.getUserPhone(request);
        //调用express的service.通过用户手机号查询其所有快递信息
        ExpressServiceImpl expressService = new ExpressServiceImpl();
        List<Express> expressList = expressService.selectByPhone(userPhone);
        if (expressList.size() > 0) {
            //将快递信息分类 分为已取 未取
            Stream<Express> expressStatus1 = expressList.stream().filter(express -> {
                if (express.getStatus() == 1) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                Long time1 = DateFormatUtil.getTime(o1.getInputTime1());
                long time2 =DateFormatUtil.getTime(o2.getInputTime1());
                return (int) (time1 - time2);
            });
            //已取快递
            Stream<Express> expressStatus0 = expressList.stream().filter(express -> {
                if (express.getStatus() == 0) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                Long time1 = DateFormatUtil.getTime(o1.getOutputTime1());
                long time2 = DateFormatUtil.getTime(o2.getInputTime1());
                return (int) (time1 - time2);
            });
            Object[] st1 = expressStatus1.toArray();
            Object[] st0 = expressStatus0.toArray();

            List<Object> list = new ArrayList<>();
            list.add(st1);
            list.add(st0);
            data = new Message(1,"查询成功",list);
        }else{
            data = new Message(0,"没有查询到任何快递信息");
        }
        return JsonUtil.toJSON(data);
    }

    /**
     * 新用户注册时的验证码,修改用户信息时的验证码
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/getNewCode.do")
    public String getNewUserCode(HttpServletRequest request, HttpServletResponse response){
        Message data = null;
        String userPhone = request.getParameter("userPhone");
        //给用户发送验证码
        String newCode = RandomUtil.getRandom();
        System.out.println("您的验证码时" + newCode);
        if (newCode != null){
            data = new Message(1,"验证码已发送，请注意查收");
            request.getSession().setAttribute("newPhone",userPhone);
            request.getSession().setAttribute("newCode",newCode);
        }else{
            data = new Message(0,"验证码发送失败，请重新点击发送");
        }
        return JsonUtil.toJSON(data);
    }

    /**
     * 新用户的信息完善
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/newUserSubmit.do")
    public String newUser(HttpServletRequest request, HttpServletResponse response){
        Message data = null;
        String userName = request.getParameter("userName");
        String IDCard = request.getParameter("IDCard");
        String userPhone = request.getParameter("userPhone");
        String password = request.getParameter("password");
        String code = request.getParameter("msg");
        //判断验证码输入是否正确
        HttpSession session = request.getSession();
        Object newPhone = session.getAttribute("newPhone");
        Object newCode = session.getAttribute("newCode");
        if (!newPhone.equals(userPhone)){
            data = new Message(-3,"该号码未获取验证码");
        }else if(newPhone.equals(userPhone)&&newCode.equals(code)){
            User user = new User(userName,IDCard,0,password,userPhone);
            //调用service
            UserServiceImpl userService = new UserServiceImpl();
            Integer integer = userService.insertUser(user);
            if (integer == 1){
                data = new Message(1, "注册成功");
            }else if (integer == 0){
                data = new Message(0,"用户名重复");
            }else if (integer == -1){
                data = new Message(-1,"该手机号已被注册");
            }else{
                data = new Message(-2,"注册失败");
            }
        }
        return JsonUtil.toJSON(data);
    }

    /**
     * 修改用户信息,先判断是快递员 还是普通用户
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/userUpdate.do")
    public String updateUser(HttpServletRequest request, HttpServletResponse response){
        Message data = null;
        Integer integer = null;
        String userName = request.getParameter("userName");
        String IDCard = request.getParameter("IDCard");
        String userPhone = request.getParameter("userPhone");
        String password = request.getParameter("password");
        String code = request.getParameter("msg");
        //判断验证码输入是否正确
        HttpSession session = request.getSession();
        Object newPhone = session.getAttribute("newPhone");
        Object newCode = session.getAttribute("newCode");
        if (!newPhone.equals(userPhone)){
            data = new Message(-3,"该号码未获取验证码");
        }else if(newPhone.equals(userPhone)&&newCode.equals(code)){
            //确认可以修改，判断修改用户的是否 快递员 还是 普通用户
            Role role = UserUtils.getRole(request);

            if (role.getRoleId() == 1){
                //快递员的修改
                Courier courier = (Courier) role.getObject();
                courier.setCourierName(userName);
                courier.setIDCard(IDCard);
                courier.setCourierPhone(userPhone);
                courier.setPassword(password);
                CourierServiceImpl courierService = new CourierServiceImpl();
                integer = courierService.updateCourier(courier);
            }else if (role.getRoleId() == 2) {
                //普通用户的修改
                User user = (User) role.getObject();
                user.setUserName(userName);
                user.setIDCard(IDCard);
                user.setUserPhone(userPhone);
                user.setPassword(password);
                UserServiceImpl userService = new UserServiceImpl();
                integer = userService.updateUser(user);
            }

            if (integer == 1){
                data = new Message(1, "修改成功");
            }else if (integer == 0){
                data = new Message(0,"用户名重复");
            }else if (integer == -1){
                data = new Message(-1,"该手机号已被注册");
            }else{
                data = new Message(-2,"修改失败");
            }
        }
        return JsonUtil.toJSON(data);
    }



}
